const Router = require('koa-router')
const router = new Router({
  prefix: '/api'
})
const query = require('../db/query')
const path = require('path')
const fs = require('fs')
const cache = require('../middleware/cache')

// 获取所有教师列表（原有接口）- 添加缓存，缓存时间300秒
router.get('/teachers', cache({ expire: 300 }), async (ctx) => {
  try {
    const sql = `
      SELECT id, name 
      FROM teachers 
      ORDER BY id ASC
    `
    const result = await query(sql)
    ctx.body = {
      code: 0,
      data: result,
      msg: 'success'
    }
  } catch (error) {
    ctx.body = {
      code: 1,
      msg: error.message
    }
  }
})

// 获取教师课程列表
router.get('/teacher/courses', async (ctx) => {
  try {
    const { teacherId } = ctx.query;
    const sql = `
      SELECT c.*, 
        COUNT(DISTINCT b.id) as booking_count,
        AVG(cc.rating) as average_rating
      FROM courses c
      LEFT JOIN bookings b ON c.id = b.course_id
      LEFT JOIN course_comments cc ON c.id = cc.course_id
      WHERE c.teacher_id = ?
      GROUP BY c.id
      ORDER BY c.create_time DESC
    `;
    const result = await query(sql, [teacherId]);
    ctx.body = {
      code: 0,
      data: result,
      msg: 'success'
    }
  } catch (error) {
    ctx.body = {
      code: 1,
      msg: error.message
    }
  }
})

// 获取教师预约列表
router.get('/teacher/bookings', async (ctx) => {
  try {
    const { status, dateFrom, dateTo, teacherId } = ctx.query;
    let sql = `
      SELECT b.*, c.title as course_title
      FROM bookings b
      JOIN courses c ON b.course_id = c.id
      WHERE c.teacher_id = ?
    `;
    const params = [teacherId];

    if (dateFrom) {
      sql += ' AND DATE(b.booking_date) >= ?';  // 使用 DATE() 函数只比较日期部分
      params.push(dateFrom);
    }
    if (dateTo) {
      sql += ' AND DATE(b.booking_date) <= ?';  // 使用 DATE() 函数只比较日期部分
      params.push(dateTo);
    }
    if (status) {
      sql += ' AND b.status = ?';
      params.push(status);
    }

    sql += ' ORDER BY b.booking_date ASC';  // 按日期升序排序
    const result = await query(sql, params);
    ctx.body = {
      code: 0,
      data: result,
      msg: 'success'
    }
  } catch (error) {
    ctx.body = {
      code: 1,
      msg: error.message
    }
  }
})

// 更新预约状态
router.put('/teacher/bookings/:id/status', async (ctx) => {
  try {
    const { id } = ctx.params;
    const { status, remark } = ctx.request.body;
    const sql = `
      UPDATE bookings 
      SET status = ?, remark = ?
      WHERE id = ?
    `;
    await query(sql, [status, remark, id]);
    ctx.body = {
      code: 0,
      msg: '预约状态更新成功'
    }
  } catch (error) {
    ctx.body = {
      code: 1,
      msg: error.message
    }
  }
})

// 获取课程评价
router.get('/teacher/courses/:courseId/comments', async (ctx) => {
  try {
    const { courseId } = ctx.params;
    const sql = `
      SELECT cc.*, u.name as user_name, u.avatar as user_avatar
      FROM course_comments cc
      JOIN users u ON cc.user_id = u.id
      WHERE cc.course_id = ?
      ORDER BY cc.created_at DESC
    `;
    const result = await query(sql, [courseId]);
    ctx.body = {
      code: 0,
      data: result,
      msg: 'success'
    }
  } catch (error) {
    ctx.body = {
      code: 1,
      msg: error.message
    }
  }
})

// 获取教师统计数据 - 添加缓存，缓存时间120秒
router.get('/teacher/statistics', cache({ expire: 120 }), async (ctx) => {
  try {
    const { teacherId } = ctx.query;
    const stats = {};
    
    // 获取课程总数
    const coursesCountSql = 'SELECT COUNT(*) as total FROM courses WHERE teacher_id = ?';
    const [coursesCount] = await query(coursesCountSql, [teacherId]);
    stats.totalCourses = coursesCount.total;

    // 获取学生总数
    const studentsCountSql = `
      SELECT COUNT(DISTINCT user_id) as total 
      FROM bookings b
      JOIN courses c ON b.course_id = c.id
      WHERE c.teacher_id = ?
    `;
    const [studentsCount] = await query(studentsCountSql, [teacherId]);
    stats.totalStudents = studentsCount.total;

    // 获取平均评分
    const ratingsSql = `
      SELECT AVG(cc.rating) as average
      FROM course_comments cc
      JOIN courses c ON cc.course_id = c.id
      WHERE c.teacher_id = ?
    `;
    const [ratings] = await query(ratingsSql, [teacherId]);
    stats.averageRating = ratings.average || 0;

    ctx.body = {
      code: 0,
      data: stats,
      msg: 'success'
    }
  } catch (error) {
    ctx.body = {
      code: 1,
      msg: error.message
    }
  }
})

// 获取教师个人信息
router.get('/teacher/profile/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const sql = `
      SELECT id, name, avatar, title, description
      FROM teachers
      WHERE id = ?
    `;
    const [teacher] = await query(sql, [id]);
    
    if (teacher) {
      ctx.body = {
        code: 0,
        data: teacher,
        msg: 'success'
      }
    } else {
      ctx.body = {
        code: 1,
        msg: '教师不存在'
      }
    }
  } catch (error) {
    console.error('获取教师信息失败:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    }
  }
})

// 更新教师个人信息
router.put('/teacher/profile/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const updateData = ctx.request.body;
    
    const sql = `
      UPDATE teachers
      SET username = ?, name = ?, title = ?, email = ?, phone = ?, description = ?, avatar = ?
      WHERE id = ?
    `;
    
    await query(sql, [
      updateData.username,
      updateData.name,
      updateData.title,
      updateData.email,
      updateData.phone,
      updateData.description,
      updateData.avatar,
      id
    ]);

    // 获取更新后的数据
    const [updatedTeacher] = await query(
      'SELECT id, username, name, title, email, phone, avatar, description FROM teachers WHERE id = ?',
      [id]
    );
    
    ctx.body = {
      code: 0,
      msg: '更新成功',
      data: updatedTeacher
    };
  } catch (error) {
    console.error('更新教师信息错误:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 头像上传处理
router.post('/teacher/upload/avatar/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const file = ctx.request.files?.avatar;
    
    if (!file) {
      throw new Error('没有接收到上传文件');
    }

    // 确保是图片文件
    if (!file.mimetype.startsWith('image/')) {
      throw new Error('只允许上传图片文件');
    }

    // 获取原有的头像URL
    const queryResult = await query('SELECT avatar FROM teachers WHERE id = ?', [id]);
    const oldAvatarUrl = queryResult[0]?.avatar;

    // 设置新的文件名和路径
    const newImageUrl = `/uploads/images/teachers/teacher${id}.jpg`;
    const targetPath = path.join(__dirname, '../public', newImageUrl);
    
    // 确保目标目录存在
    const targetDir = path.dirname(targetPath);
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true });
    }

    // 删除原有头像文件
    if (oldAvatarUrl) {
      const oldPath = path.join(__dirname, '../public', oldAvatarUrl);
      if (fs.existsSync(oldPath)) {
        fs.unlinkSync(oldPath);
      }
    }

    // 移动新文件到目标位置
    const reader = fs.createReadStream(file.filepath);
    const writer = fs.createWriteStream(targetPath);
    await new Promise((resolve, reject) => {
      reader.pipe(writer);
      writer.on('finish', resolve);
      writer.on('error', reject);
    });

    // 删除临时文件
    if (fs.existsSync(file.filepath)) {
      fs.unlinkSync(file.filepath);
    }

    // 更新数据库中的头像URL
    await query(
      'UPDATE teachers SET avatar = ? WHERE id = ?',
      [newImageUrl, id]
    );

    ctx.body = {
      code: 0,
      msg: '头像上传成功',
      data: {
        url: newImageUrl
      }
    };
  } catch (error) {
    console.error('头像上传失败:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 教师登录
router.post('/teacher/login', async (ctx) => {
  try {
    const { username, password } = ctx.request.body;
    
    const sql = `
      SELECT id, username, name, title, avatar 
      FROM teachers 
      WHERE username = ? AND password = ?
    `;
    const [teacher] = await query(sql, [username, password]);

    if (teacher) {
      const token = 'temp_token_' + Date.now();
      
      // 设置 httpOnly cookie
      ctx.cookies.set('token', token, {
        httpOnly: true,  // 防止 JavaScript 访问
        maxAge: 24 * 60 * 60 * 1000,  // 1天过期
        path: '/',
        secure: process.env.NODE_ENV === 'production',  // 生产环境使用 HTTPS
        sameSite: 'strict'
      });
      
      ctx.body = {
        code: 0,
        msg: '登录成功',
        data: {
          user: {
            ...teacher,
            password: undefined
          }
        }
      };
    } else {
      ctx.body = {
        code: 1,
        msg: '用户名或密码错误'
      };
    }
  } catch (error) {
    console.error('登录失败:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 教师登出
router.post('/teacher/logout', (ctx) => {
  ctx.cookies.set('token', null);  // 清除 cookie
  ctx.body = {
    code: 0,
    msg: '登出成功'
  };
});

module.exports = router